var app = getApp();
Page({
  data: {
    checked:true
  },
  change(e){
    var checked = e.currentTarget.dataset.checked
    if(!checked){
      this.setData({
        checked:true
      })
    } else {
      this.setData({
        checked: false
      })
    }
  },
  onShow: function () {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          console.log("已授权")
          wx.showLoading({ title: "启动中..." })
          var that = this
          var cookie = app.globalData.cookie
          console.log("cookie:" + cookie)
          if (!cookie && cookie == undefined) {
            wx.login({
              success: res => {
                this.login(res.code)
              }
            })
          } else {
            wx.navigateBack({
              delta: 1
            })
          }
        } else {
          //显示授权按钮
        }
      }
    })
  },
  login: function (code) {
    console.log('重新登录')
    wx.getUserInfo({
      withCredentials: true,
      success: res => {
        app.globalData.AlreadyJumpedLogin = true
        app.request({
          url: '/home/login',
          method: "POST",
          data: { code: code, signature: res.signature, rawData: res.rawData, encryptedData: res.encryptedData, iv: res.iv },
          success: function (res, header) {
            wx.hideLoading()
            console.log(res)
            if (res && res.result && res.result) {
              wx.setStorage({
                key: 'token', 
                data: {
                  member_id: res.result.member_id,
                  openid: res.result.openid
                }
              })
              wx.navigateBack({
                delta: 1
              })
            }
          },
          complete: function (res) {
            app.globalData.AlreadyJumpedLogin = false
          }
        })
      }
    })

  },
  bindGetUserInfo: function (e) {
    //用户按了允许授权按钮
    if (e.detail.userInfo) {
      this.onShow()
    } else {
      wx.showToast({ title: "授权失败，请重试", icon: "none", duration: 2000 })
    }
  },
  loadPrivte() {
    let self = this
    app.request({
      url: '/home/api/server',
      method: 'POST',
      success: (res) => {
        console.log(res.result.server)
        self.downloadPdf(res.result.server)
        // var article = res.result.detail;
        // WxParse.wxParse('article', 'html', article, self, 5);
        // self.setData({
        //   info: res.result
        // })
      }
    })
  },
  downloadPdf(url) {
    wx.downloadFile({
      url: url,
      success(res) {
        const filePath = res.tempFilePath
        wx.openDocument({
          filePath,
          success(res) {
            console.log('打开文档成功')
          }
        })
      }
    })
  }
})